<template>
  <div class="tag-difficulty-analysis">
    <h2>算法掌握情况</h2>
    <div class="sort-options">
      <label>排序：</label>
      <select v-model="sortField">
        <option value="mastery_score">按掌握分</option>
        <option value="mastery_level">按掌握度</option>
        <option value="recommendation_score">按推荐分</option>
      </select>
      <button @click="toggleSortOrder">{{ sortOrder === 'asc' ? '升序' : '降序' }}</button>
    </div>
    <table>
      <thead>
        <tr>
          <th>标签</th>
          <th v-for="difficulty in difficultyLevels" :key="difficulty">{{ difficulty }}</th>
          <th>总计</th>
          <th>掌握分</th>
          <th>掌握度</th>
          <th>推荐分</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="tag in sortedTags" :key="tag.index">
          <td>{{ tag.tag_name }}</td>
          <td
            v-for="difficulty in difficultyLevels"
            :key="difficulty"
            class="cell"
            @mouseenter="showProblems(tag.index, difficulty)"
            @mouseleave="hideProblems"
          >
            {{ tagDifficultyData[tag.tag_name]?.difficulties[difficulty]?.count || 0 }}
            <div v-if="isExpanded(tag.index, difficulty)" class="problem-tooltip">
              <div
                v-for="problem in tagDifficultyData[tag.tag_name]?.difficulties[difficulty]?.problems || []"
                :key="problem[0]"
                class="problem-item"
              >
                <a :href="getProblemLink(problem[0])" target="_blank">{{ problem[0] }} - {{ problem[1] }}</a>
              </div>
            </div>
          </td>
          <td>{{ tagDifficultyData[tag.tag_name]?.total || 0 }}</td>
          <td>{{ tagMasteryData[tag.tag_name]?.mastery_score?.toFixed(2) || 0 }}</td>
          <td>{{ tagMasteryData[tag.tag_name]?.mastery_level?.toFixed(2) || 0 }}</td>
          <td>{{ tagMasteryData[tag.tag_name]?.recommendation_score?.toFixed(2) || 0 }}</td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td>总计</td>
          <td v-for="difficulty in difficultyLevels" :key="difficulty">
            {{ totalProblemsByDifficulty[difficulty] || 0 }}
          </td>
          <td>{{ totalProblems }}</td>
          <td colspan="3"></td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
import axios from '@/axios';

export default {
  name: 'TagDifficultyAnalysis',
  data() {
    return {
      tags: [],
      tagDifficultyData: {},
      tagMasteryData: {},
      totalProblems: 0,
      totalProblemsByDifficulty: {},
      sortField: 'mastery_score',
      sortOrder: 'desc',
      difficultyLevels: ['入门', '普及-', '普及/提高-', '普及+/提高', '提高+/省选-', '省选/NOI-', 'NOI/NOI+/CTSC', '暂未评定'],
      hoveredCell: { tag: null, difficulty: null }
    };
  },
  computed: {
    sortedTags() {
      let sorted = [...this.tags];
      if (this.sortField) {
        sorted = sorted.sort((a, b) => {
          const fieldA = this.tagMasteryData[a.tag_name]?.[this.sortField] || 0;
          const fieldB = this.tagMasteryData[b.tag_name]?.[this.sortField] || 0;
          return this.sortOrder === 'asc' ? fieldA - fieldB : fieldB - fieldA;
        });
      }
      return sorted;
    }
  },
  methods: {
    async fetchTagDifficultyData() {
      try {
        const [tagsResponse, difficultyResponse, masteryResponse] = await Promise.all([
          axios.get('/api/tag/'),
          axios.get('/api/recommendation/frontend_get_user_tag_difficulty_analysis/'),
          axios.get('/api/algorithm/frontend_get_user_tag_mastery/')
        ]);

        this.tags = tagsResponse.data;
        this.tagDifficultyData = difficultyResponse.data.tag_difficulty_data || {};
        this.totalProblems = difficultyResponse.data.total_problems || 0;
        this.totalProblemsByDifficulty = this.calculateTotalProblemsByDifficulty();
        this.tagMasteryData = masteryResponse.data.tag_mastery_data || {};
      } catch (error) {
        console.error('获取分析数据失败:', error);
      }
    },
    calculateTotalProblemsByDifficulty() {
      const totals = {};
      for (const tag in this.tagDifficultyData) {
        for (const difficulty of this.difficultyLevels) {
          const count = this.tagDifficultyData[tag].difficulties[difficulty]?.count || 0;
          totals[difficulty] = (totals[difficulty] || 0) + count;
        }
      }
      return totals;
    },
    toggleSortOrder() {
      this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc';
    },
    showProblems(tagIndex, difficulty) {
      this.hoveredCell = { tag: tagIndex, difficulty };
    },
    hideProblems() {
      this.hoveredCell = { tag: null, difficulty: null };
    },
    isExpanded(tagIndex, difficulty) {
      return this.hoveredCell.tag === tagIndex && this.hoveredCell.difficulty === difficulty;
    },
    getProblemLink(problemNumber) {
      return `https://www.luogu.com.cn/problem/${problemNumber}`;
    }
  },
  mounted() {
    this.fetchTagDifficultyData();
  }
};
</script>

<style scoped>
.tag-difficulty-analysis {
  max-width: 70%;
  margin: 20px auto;
  padding: 10px 20px;
  background-color: #f5f5f5;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

table {
  max-width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: center;
}

thead th {
  background-color: #007bff;
  color: white;
}

td {
  background-color: #e9f7fe;
  position: relative;
}

.cell {
  cursor: pointer;
  border: 1px solid #ddd;
}

.problem-tooltip {
  position: absolute;
  top: 100%;
  left: 0;
  background-color: white;
  border: 1px solid #ddd;
  padding: 5px 10px;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  z-index: 1;
  width: 280px; /* 细长横条显示 */
  display: flex;
  flex-direction: column;
}

.problem-item {
  background-color: #007bff;
  color: white;
  padding: 5px 8px;
  border-radius: 4px;
  margin: 3px 0;
  font-size: 14px;
  text-align: left;
  white-space: nowrap; /* 单行显示 */
  overflow: hidden;
  text-overflow: ellipsis;
}

.problem-tooltip a {
  color: white;
  text-decoration: none;
}

.sort-options {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.sort-options label {
  margin-right: 10px;
  font-weight: bold;
}

.sort-options button {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 5px 10px;
  margin-left: 5px;
  border-radius: 4px;
  cursor: pointer;
}
</style>
